<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Stock List</title>
    <!-- Bootstrap 4 CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <!-- jQuery -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <!-- Popper JS -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <!-- Bootstrap 4 JS -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <!-- Date Range Picker -->
    <!-- Moment.js -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

    <link rel="stylesheet" type="text/css"
          href="https://cdn.jsdelivr.net/npm/bootstrap-daterangepicker@3.1.0/daterangepicker.css"/>
    <script type="text/javascript"
            src="https://cdn.jsdelivr.net/npm/bootstrap-daterangepicker@3.1.0/daterangepicker.js"></script>
    <style>
        .input-button-container {
            display: flex;
            justify-content: center;
            gap: 1rem;
            margin-bottom: 1rem;
        }

        .custom-input-width {
            width: 550px;
        }

        .custom-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            height: auto;
            margin-bottom: 1rem;
        }

        .custom-header > * {
            flex: 1;
        }

        .centered-title {
            width: 100%;
            text-align: center;
        }

        body {
            padding: 2rem;
        }

        .filter-container {
            display: flex;
            flex-wrap: wrap;
            gap: 1rem;
            justify-content: center;
        }

        .filter-container select, .filter-container input {
            width: 200px;
        }

        table {
            margin: 2rem auto;
        }

        .pagination {
            display: flex;
            flex-wrap: wrap;
        }

        .page-item {
            margin-right: 5px;
        }
    </style>
</head>
<body>
{#<header>#}
{#        <nav>#}
{#            {% if user.is_authenticated %}#}
{#                <span>Welcome, {{ user.username }}!</span>#}
{#                <a href="{% url 'logout' %}">注销</a>#}
{#            {% else %}#}
{#                <a href="{% url 'login' %}">登入</a>#}
{#                <a href="{% url 'register' %}">注册</a>#}
{#            {% endif %}#}
{#        </nav>#}
{#    </header>#}
<div class="container">
    <div class="input-button-container">
        <input type="text" id="custom-input" class="form-control custom-input-width"
               placeholder="输入预测天数(不要超过7，否则效果差。且预测和更新都非常耗时)" value=3>
{#        <button id="predict-stock-button" class="btn btn-dark">预测股票</button>#}
        <button id="update-stock-button" class="btn btn-primary">更新股票</button>
        <a href="/stock/stock_comparison" class="btn btn-primary">对比股票</a>
        <a href="/stock/market_index" class="btn btn-primary">大盘指数</a>

    </div>
    <br>
    <h1 class="centered-title">股票列表</h1>

    <div class="filter-container">

        <input type="text" id="name-filter" class="filter form-control" placeholder="搜索股票">
        <select id="area-filter" class="filter form-control">
            <option value="">地区</option>
        </select>
        <select id="industry-filter" class="filter form-control">
            <option value="">行业</option>
        </select>
        <input type="text" id="list-date-filter" class="filter form-control" placeholder="日期筛选">

    </div>


    <table class="table table-striped table-bordered">
        <thead class="thead-dark">
        <tr>
            <th>序号</th>
            <th>股票代码</th>
            <th>名称</th>
            <th>地区</th>
            <th>行业</th>
            <th>日期</th>
            <th>开盘价</th>
            <th>收盘价</th>
            <th>变化率</th>
            <th>成交量</th>
            <th>总量</th>
        </tr>
        </thead>
        <tbody id="table-body">
        {% for row in data %}
            <tr>
                {% for key, value in row.items %}
                    <td>
                        {% if key == 'ts_code' %}
                            <a href="/stock/{{ value }}">{{ value }}</a>
                        {% else %}
                            {{ value }}
                        {% endif %}
                    </td>
                {% endfor %}
            </tr>
        {% endfor %}
        </tbody>
    </table>

    <br/><br/>
    <nav aria-label="Page navigation example">
        <ul class="pagination">
            {% if data.has_previous %}
                <li class="page-item">
                    <a class="page-link" href="?page=1" aria-label="First">
                        <span aria-hidden="true">&laquo;</span>
                    </a>
                </li>
                <li class="page-item">
                    <a class="page-link" href="?page={{ data.previous_page_number }}" aria-label="Previous">
                        <span aria-hidden="true">&lsaquo;</span>
                    </a>
                </li>
            {% else %}
                <li class="page-item disabled">
                    <a class="page-link" href="#" tabindex="-1" aria-disabled="true">&laquo;</a>
                </li>
                <li class="page-item disabled">
                    <a class="page-link" href="#" tabindex="-1" aria-disabled="true">&lsaquo;</a>
                </li>
            {% endif %}

            {% for i in data.paginator.page_range %}
                {% if data.number == i %}
                    <li class="page-item active"><a class="page-link" href="?page={{ i }}">{{ i }}</a></li>
                {% else %}
                    <li class="page-item"><a class="page-link" href="?page={{ i }}">{{ i }}</a></li>
                {% endif %}
            {% endfor %}

            {% if data.has_next %}
                <li class="page-item">
                    <a class="page-link" href="?page={{ data.next_page_number }}" aria-label="Next">
                        <span aria-hidden="true">&rsaquo;</span>
                    </a>
                </li>
                <li class="page-item">
                    <a class="page-link" href="?page={{ data.paginator.num_pages }}" aria-label="Last">
                        <span aria-hidden="true">&raquo;</span>
                    </a>
                </li>
            {% else %}
                <li class="page-item disabled">
                    <a class="page-link" href="#" tabindex="-1" aria-disabled="true">&rsaquo;</a>
                </li>
                <li class="page-item disabled">
                    <a class="page-link" href="#" tabindex="-1" aria-disabled="true">&raquo;</a>
                </li>
            {% endif %}
        </ul>
    </nav>

</div>


<script>
    function updateTable(data) {
        let table_body = $('#table-body');
        table_body.empty();

        data.forEach(function (row) {
            let tr = $('<tr>');
            for (const [key, value] of Object.entries(row)) {
                let td = $('<td></td>');
                if (key === 'ts_code') {
                    let a = $('<a></a>').attr('href', '/stock/' + value).text(value);
                    td.append(a);
                } else {
                    td.text(value);
                }
                tr.append(td);
            }
            table_body.append(tr);
        });
    }

    function getFilters() {
        return {
            'name': $('#name-filter').val(),
            'area': $('#area-filter').val(),
            'industry': $('#industry-filter').val(),
            {#'market': $('#market-filter').val(),#}
            'list_date': $('#list-date-filter').val()
        };
    }

    function filterData() {
        let filters = JSON.stringify(getFilters());

        $.ajax({
            type: 'POST',
            url: '/stock/filter_data/',
            data: {
                'filters': filters,
                'csrfmiddlewaretoken': '{{ csrf_token }}'
            },
            dataType: 'json',
            success: function (response) {
                updateTable(response.data);
            },
            error: function (error) {
                console.error(error);
            }
        });
    }

    function loadFilterOptions() {
        $.ajax({
                type: 'GET',
                url: '/stock/filter_options/',
                dataType: 'json',
                success: function (response) {
                    console.log(response)

                    $('#area-filter').append(response.area.map(function (item) {
                        return $('<option></option>').val(item).text(item);
                    }));
                    $('#industry-filter').append(response.industry.map(function (item) {
                        return $('<option></option>').val(item).text(item);
                    }));
                    //$('#market-filter').append(response.market.map(function (item) {
                    //  return $('<option></option>').val(item).text(item);
                    //}));
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    console.error('Error: ' + textStatus + ', ' + errorThrown);
                }

            }
        )
        ;
    }

    function updateAllStock() {
        $.ajax({
            type: 'GET',
            url: '/stock/actions/updateAllStock/',
            dataType: 'json',
            success: function (response) {
                // 根据您的需求处理响应数据，例如更新表格等
                console.log(response);
            },
            error: function (error) {
                console.error(error);
            }
        });
    }

    function predict() {
        let inputValue = $('#custom-input').val().trim();
        // 检查输入框的值是否为空或者非数字
        if (inputValue === '' || isNaN(inputValue)) {
            inputValue = 5;
        }
        $.ajax({
            type: 'GET',
            url: '/stock/actions/predict/stocks',
            data: {
                'n_step': inputValue
            },
            dataType: 'json',

            success: function (response) {
                // 根据您的需求处理响应数据，例如更新表格等
                console.log(response);

                // 将响应数据存储到localStorage或sessionStorage中
                // 以便在predictList.html页面中访问
                localStorage.setItem('results', JSON.stringify(response.data));

                // 跳转到predictList.html页面
                window.location.href = '/stock/actions/predictList/';
            },
            error: function (error) {
                console.error(error);
            }
        });
    }


    $(document).ready(function () {



        $('.filter').on('change', function () {
            filterData();
        });
        // 更新所有股票
        $('#update-stock-button').on('click', function () {
            updateAllStock();
        });
        // 预测股票
        $('#predict-stock-button').on('click', function () {
            //precit
            const input = document.getElementById('custom-input');
            const n = input.value;
            window.location.href =  `/stock/actions/predict/stocks?n_step=${n}`;
        });


        $('#list-date-filter').daterangepicker({
            autoUpdateInput: false,
            locale: {
                cancelLabel: 'Clear'
            }
        });

        $('#list-date-filter').on('apply.daterangepicker', function (ev, picker) {
            $(this).val(picker.startDate.format('YYYY-MM-DD') + ' - ' + picker.endDate.format('YYYY-MM-DD'));
            filterData();
        });

        $('#list-date-filter').on('cancel.daterangepicker', function (ev, picker) {
            $(this).val('');
            filterData();
        });

        loadFilterOptions();
    });
</script>
</body>
</html>